package main

import (
	"fmt"
	"net"
	"time"
	. "tksLog"
	. "tksStatic"
	. "tksTcp"
	. "tksUint"
)

var GateClient, LsClient *TksTcpConn
var ConnectedGate bool = false

func ClientLoginRsp(conn net.Conn, from uint32, to uint32, buf []byte) {
	json, err := BufToMsg(buf)
	if err != nil {
		Debug("message error")
		return
	}
	ret, _ := json.Get("R").Int()
	token, _ := json.Get("Token").String()
	Debug("get login rsp, ret: %d from %s, token: %s", ret, conn.RemoteAddr().String(), token)
	//
	ConnectGate(token)
}

func ClientEnrollRsp(conn net.Conn, from uint32, to uint32, buf []byte) {
	json, err := BufToMsg(buf)
	if err != nil {
		Debug("message error")
		return
	}
	ret, _ := json.Get("R").Int()
	token, _ := json.Get("R").String()
	Debug("get enroll rsp, ret: %d from %s, token: %s", ret, conn.RemoteAddr().String(), token)
	//
	ConnectGate(token)
}

func ConnectGateRsp(conn net.Conn, from uint32, to uint32, buf []byte) {
	json, err := BufToMsg(buf)
	if err != nil {
		Debug("message error")
		return
	}
	ret, _ := json.Get("R").Int()
	Debug("get Connect Gate rsp, ret: %d from %s", ret, conn.RemoteAddr().String())
	//
	ConnectedGate = true
}

func cbGateHeartbeatRsp(conn net.Conn, from uint32, to uint32, buf []byte) {
	Debug("get Heartbeat Gate rsp from %s", conn.RemoteAddr().String())
}

func registerCmd() {
	RegisterServerCmd(CmdLoginRsp, ClientLoginRsp)
	RegisterServerCmd(CmdEnrollRsp, ClientEnrollRsp)
	RegisterServerCmd(CmdClientConnectGateRsp, ConnectGateRsp)
	RegisterServerCmd(CmdGateHeartbeatRsp, cbGateHeartbeatRsp)
}

/*******************************************/
func sendLogin(conn net.Conn) {
	var req LoginReq
	req.User = "guang23"
	req.Pwd = "123123"
	data, _ := MsgToBuf(req)
	Debug("send to server: %s, data %s", conn.RemoteAddr().String(), string(data))
	SendBuffer(conn, CmdLoginReq, 0xFFFF, 0xFFFF, data)
}

func sendEnroll(conn net.Conn) {
	var req LoginReq
	req.User = "guang23"
	req.Pwd = "123123"
	data, _ := MsgToBuf(req)
	SendBuffer(conn, CmdEnrollReq, 0xFFFF, 0xFFFF, data)
}

func sendConnectGateReq(conn net.Conn, token string) {
	var req ClientConnectGateReq
	req.ServerId = 1
	req.Token = token
	data, _ := MsgToBuf(req)
	SendBuffer(conn, CmdClientConnectGateReq, 0xFFFF, 0, data)
}

func sendHeartbeatGateReq(conn net.Conn) {
	Debug("=====2====")
	var req GateHeartbeatReq
	req.Any = true
	data, _ := MsgToBuf(req)
	SendBuffer(conn, CmdGateHeartbeatReq, 0xFFFF, 0, data)
}

func ConnectGate(token string) {
	client, err := NewClient("127.0.0.1:9079")
	if err != nil {
		fmt.Println(err)
	}
	GateClient = client
	sendConnectGateReq(GateClient.Conn, token)
}

func ConnectLoginServer() {
	client, err := NewClient("127.0.0.1:9070")
	if err != nil {
		fmt.Println(err)
	}
	LsClient = client
	sendLogin(LsClient.Conn)
	// sendEnroll(LsClient.Conn)
}

func main() {
	InitLogger("client")
	//
	registerCmd()
	//
	ConnectLoginServer()
	//
	for {
		time.Sleep(5 * time.Second)
		if ConnectedGate {
			sendHeartbeatGateReq(GateClient.Conn)
		}
	}
}
